<template>
  <div
    v-if="isExternal"
    :style="styleExternalIcon"
    class="svg-external-icon svg-icon"
    v-on="$listeners"
  />
  <i v-else-if="isIIcon" :class="iIconClass" :style="iStyle"></i>
  <svg
    v-else
    :class="svgClass"
    :style="svgStyle"
    aria-hidden="true"
    v-on="$listeners"
  >
    <use :xlink:href="iconName" />
  </svg>
</template>

<script>
import { isExternal } from '@/utils/validate'

export default {
  name: 'SvgIcon',
  props: {
    iconClass: {
      type: String,
      required: true
    },
    className: {
      type: String,
      default: ''
    },
    size: {
      default: [Number, String],
      default: 1
    },
    color: {
      type: String
    }
  },
  computed: {
    svgStyle() {
      if (typeof this.size === 'number') {
        return {
          width: this.size + 'rem',
          height: this.size + 'rem',
          color: this.color
        }
      } else {
        return { width: this.size, height: this.size, color: this.color }
      }
    },
    iStyle() {
      if (typeof this.size === 'number') {
        return { fontSize: this.size + 'rem', color: this.color }
      } else {
        return { fontSize: this.size, color: this.color }
      }
    },
    isExternal() {
      return isExternal(this.iconClass)
    },
    isIIcon() {
      const reg = /^el-|vxe-/
      return reg.test(this.iconClass)
    },
    iconName() {
      return `#icon-${this.iconClass}`
    },
    svgClass() {
      if (this.className) {
        return 'svg-icon ' + this.className
      } else {
        return 'svg-icon'
      }
    },
    styleExternalIcon() {
      return {
        mask: `url(${this.iconClass}) no-repeat 50% 50%`,
        '-webkit-mask': `url(${this.iconClass}) no-repeat 50% 50%`,
        width: this.size + 'rem',
        height: this.size + 'rem'
      }
    },
    iIconClass() {
      if (this.iconClass.includes('vxe-icon')) {
        return `vxe-icon ${this.iconClass} ${this.svgClass}`
      } else {
        return `${this.iconClass} ${this.svgClass}`
      }
    }
  }
}
</script>

<style scoped>
.svg-icon {
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.svg-external-icon {
  background-color: currentColor;
  mask-size: cover !important;
  display: inline-block;
}
</style>
